package com.tpo.jnotes.loader.jarloader;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

import com.dropbox.client2.exception.DropboxException;
import com.tpo.jnotes.base.constants.BConstants;
import com.tpo.jnotes.base.logging.BLogging;
import com.tpo.jnotes.loader.dropbox.LDropboxDownloader;
import com.tpo.jnotes.loader.view.LMainSplashScreen;

public class LLoaderVersion
{

    public static String getVersionFromFile( File file ) throws IOException
    {
        String version = "0";
        BufferedReader br = null;
        try
        {
            br = new BufferedReader( new FileReader( file ) );
            version = br.readLine();
        }
        finally
        {
            if( br != null )
                br.close();
        }
        return version;
    }

    public static String getCurrentVersion()
    {
        try
        {
            return getVersionFromFile( new File( BConstants.VERSION_FILE_NAME ) );
        }
        catch( FileNotFoundException e )
        {
            BLogging.warn( "Version file not found! Using default version number..." );
            return "0";
        }
        catch( IOException e )
        {
            BLogging.warn( "Could not get version number! Using default version number..." );
            return "0";
        }
    }

    public static void checkVersion() throws DropboxException, IOException
    {
        // File versFile1 = new File( BConstants.VERSION_FILE_NAME );
        // versFile1.delete();

        LMainSplashScreen splash = new LMainSplashScreen();
        splash.pack();
        splash.setLocationRelativeTo( null );
        splash.setVisible( true );
        String currentVersionNo = LLoaderVersion.getCurrentVersion();
        splash.setVersion( currentVersionNo );
        LDropboxDownloader.downloadFile( BConstants.VERSION_FILE_NAME );
        String newVersionNo = LLoaderVersion.getCurrentVersion();

        if( (!newVersionNo.equals( currentVersionNo )) )
        {
            splash.setStatus( "Dowloading version " + newVersionNo );
            LDropboxDownloader.downloadFile( BConstants.APP_FILE_NAME, splash.getProgressBar() );
        }

        // File versFile = new File(Constants.VERSION_FILE_NAME);
        // versFile.delete();
        // File appFile = new File(Constants.APP_FILE_NAME);
        // appFile.delete();
        // }

        splash.setVisible( false );
        splash.dispose();
    }

}
